;
(function (doc, win) {
  //图片容器
  var oImgList = doc.getElementsByClassName('J_imgList')[0],
    // 数据
    data = JSON.parse(doc.getElementById('J_data').innerHTML),
    // 渲染模板
    imgTpl = doc.getElementById('J_imgTpl').innerHTML,
    //容器下所有图片
    oImgs = doc.getElementsByClassName('list-img');

  var init = function () {
    oImgList.innerHTML = renderList(data);
    bindEvent();
    setTimeout(function () {
      window.scrollTo(0, 0);
    }, 150);
  }

  function bindEvent() {
    // 页面加载完毕时加载一部分图片
    // 页面滚动的时候也加载一部分图片
    // 利用节流函数不让频繁触发
    window.onload = window.onscroll = throttle(imgLazyLoad(oImgs), 500);
  }

  function renderList(data) {
    var list = '';
    data.forEach(function (elem) {
      list += imgTpl.replace(/{{(.*?)}}/g, function (node, key) {
        return {
          name: elem.name,
          img: elem.img
        } [key];
      })
    })
    return list;
  }

  init();
})(document, window);

function imgLazyLoad(images) {
  var imgLen = images.length,
    n = 0;

  return function () {
    // 找到可视区域高度
    var cHeight = document.documentElement.clientHeight,
      //找到滚动高度并兼容IE
      sTop = document.documentElement.scrollTop || document.body.scrollTop,
      imgItem;

    for (var i = n; i < imgLen; i++) {
      imgItem = images[i];
      //每张图片的offsetTop < cHeight + sTop证明出现在可视区域之内
      if (imgItem.offsetTop < cHeight + sTop) {
        //拿到当前项地址赋值给src
        imgItem.src = imgItem.getAttribute('data-src');
        //清除原来的data-src属性
        imgItem.removeAttribute('data-src');
        n++;
      }
    }
  }
}

function throttle(fn, delay) {
  var t = null,
    begin = new Date().getTime();

  return function () {
    var _self = this,
      args = arguments,
      cur = new Date().getTime();

    clearTimeout(t);

    if (cur - begin >= delay) {
      fn.apply(_self, args);
      begin = cur;
    } else {
      t = setTimeout(function () {
        fn.apply(_self, args);
      }, delay);
    }
  }
}




//预加载
// var oDiv = document.getElementsByTagName('div')[0];
// var imgSrcArr = [
//   'http://www.xxx.com/1.jpg',
//   'http://www.xxx.com/1.jpg',
//   'http://www.xxx.com/1.jpg'
// ];

// imgSrcArr.forEach(function (elem) {
//   var oImg = new Image();
//   oImg.src = elem;
//   oImg.style.width = '100%';

//   //图片加载完毕插入到HTML
//   oImg.onload = function () {
//     oDiv.appendChild(oImg);
//   }
// });